use serde::{Serialize, Deserialize};
use chrono::{DateTime, Utc};
use crate::storage::{DataPoint, DeviceStatus, DataQuality};
use crate::collector::CollectorStatus;

/// API响应包装器
#[derive(Debug, Serialize)]
pub struct ApiResponse<T> {
    pub success: bool,
    pub data: Option<T>,
    pub message: Option<String>,
    pub timestamp: DateTime<Utc>,
}

impl<T> ApiResponse<T> {
    pub fn success(data: T) -> Self {
        Self {
            success: true,
            data: Some(data),
            message: None,
            timestamp: Utc::now(),
        }
    }
    
    pub fn error(message: String) -> Self {
        Self {
            success: false,
            data: None,
            message: Some(message),
            timestamp: Utc::now(),
        }
    }
}

/// 数据点API模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataPointModel {
    pub point_id: String,
    pub device_id: String,
    pub name: String,
    pub value: f64,
    pub timestamp: DateTime<Utc>,
    pub quality: String,
}

impl From<DataPoint> for DataPointModel {
    fn from(dp: DataPoint) -> Self {
        Self {
            point_id: dp.point_id,
            device_id: dp.device_id,
            name: dp.name,
            value: dp.value,
            timestamp: dp.timestamp,
            quality: match dp.quality {
                DataQuality::Good => "Good".to_string(),
                DataQuality::Bad => "Bad".to_string(),
                DataQuality::Uncertain => "Uncertain".to_string(),
            },
        }
    }
}

/// 设备状态API模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceStatusModel {
    pub device_id: String,
    pub online: bool,
    pub last_communication: Option<DateTime<Utc>>,
    pub error_count: u64,
    pub last_error: Option<String>,
}

impl From<DeviceStatus> for DeviceStatusModel {
    fn from(status: DeviceStatus) -> Self {
        Self {
            device_id: status.device_id,
            online: status.online,
            last_communication: status.last_communication,
            error_count: status.error_count,
            last_error: status.last_error,
        }
    }
}

/// 写入请求模型
#[derive(Debug, Deserialize)]
pub struct WriteRequest {
    pub point_id: String,
    pub value: f64,
    pub auth_token: Option<String>,
}

/// 写入响应模型
#[derive(Debug, Serialize)]
pub struct WriteResponse {
    pub point_id: String,
    pub success: bool,
    pub message: String,
    pub timestamp: DateTime<Utc>,
}

/// 历史数据查询参数
#[derive(Debug, Deserialize)]
pub struct HistoryQuery {
    pub point_id: String,
    pub start_time: Option<DateTime<Utc>>,
    pub end_time: Option<DateTime<Utc>>,
    pub limit: Option<usize>,
}

/// 系统状态模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemStatus {
    pub collector: CollectorStatusModel,
    pub storage: StorageStatusModel,
    pub api: ApiStatusModel,
    pub uptime_seconds: u64,
}

/// 采集器状态模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectorStatusModel {
    pub running: bool,
    pub worker_count: usize,
    pub active_tasks: usize,
}

/// 存储状态模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageStatusModel {
    pub memory_points: usize,
    pub memory_usage_mb: f64,
    pub persistent_enabled: bool,
    pub db_size_mb: Option<f64>,
}

/// API状态模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiStatusModel {
    pub port: u16,
    pub websocket_connections: usize,
    pub requests_served: u64,
}

/// WebSocket消息类型
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum WebSocketMessage {
    #[serde(rename = "data_update")]
    DataUpdate {
        data: DataPointModel,
    },
    #[serde(rename = "device_status")]
    DeviceStatus {
        status: DeviceStatusModel,
    },
    #[serde(rename = "system_status")]
    SystemStatus {
        status: SystemStatus,
    },
    #[serde(rename = "error")]
    Error {
        message: String,
    },
}

/// 分页响应
#[derive(Debug, Serialize)]
pub struct PaginatedResponse<T> {
    pub items: Vec<T>,
    pub total: usize,
    pub page: usize,
    pub page_size: usize,
    pub total_pages: usize,
}

impl<T> PaginatedResponse<T> {
    pub fn new(items: Vec<T>, total: usize, page: usize, page_size: usize) -> Self {
        let total_pages = (total + page_size - 1) / page_size;
        
        Self {
            items,
            total,
            page,
            page_size,
            total_pages,
        }
    }
}

/// 查询参数
#[derive(Debug, Deserialize)]
pub struct QueryParams {
    pub page: Option<usize>,
    pub page_size: Option<usize>,
    pub device_id: Option<String>,
    pub sort: Option<String>,
    pub order: Option<String>,
}